package top.fzqblog.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.fzqblog.Utils.R;
import top.fzqblog.Utils.SaiZiUtil;
import top.fzqblog.exception.BizException;
import top.fzqblog.model.Prize;
import top.fzqblog.model.User;
import top.fzqblog.model.UserPrize;

import java.util.Date;

/**
 * Created by 抽离 on 2017/9/7 0007.
 */
@Service
public class UserService {

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void duijiang(User user, Integer id)throws BizException{
        if(id == null){
            throw new BizException("兑奖出错，请重试！");
        }
        Prize prize = new Prize().selectById(id);
        if(prize == null || prize.getStatus() == 0){
            throw new BizException("奖品不存在！");
        }
        else if(prize.getPrizeCount() <= 0){
            throw new BizException("奖品已兑完！");
        }
        else if(user == null || user.getUserStatus() == 0){
            throw new BizException("用户不存在");
        }
        else if(user.getCredits() < prize.getCredits()){
            throw new BizException("积分不足！");
        }
        else{
            user.setCredits(user.getCredits() - prize.getCredits());
            user.updateById();

            prize.setPrizeCount(prize.getPrizeCount() - 1);
            prize.updateById();

            UserPrize userPrize = new UserPrize();
            userPrize.setPrizeId(prize.getPrizeId());
            userPrize.setPrizeImgurl(prize.getPrizeImg());
            userPrize.setPrizeName(prize.getPrizeName());
            userPrize.setTel(user.getTel());
            userPrize.setUserId(user.getUserId());
            userPrize.setUserName(user.getUserName());
            userPrize.setCreateTime(new Date());
            userPrize.setStatus(0);
            userPrize.insert();
        }
    }
}
